<template>
  <ele-modal
    :form="true"
    :destroy-on-close="true"
    width="40%"
    v-model="visible"
    title="上传学生就业数据">
    <el-form ref="formRef"
             :model="form"
             :rules="rules"
             label-width="80px"
             :inline="true"
             class="statistic-file-import-form-inline"
             @submit.prevent="">
      <el-form-item label="毕业年份:" prop="graduationYear">
        <el-select
          v-model="form.year"
          clearable
          placeholder="请选择毕业年份">
          <el-option
            v-for="item in graduationYearList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据日期" prop="date">
        <el-date-picker
          v-model="form.date"
          value-format="YYYY-MM-DD"
          placeholder="请选择数据日期"
          class="ele-fluid"
        />
      </el-form-item>
    </el-form>
    <el-divider></el-divider>
    <el-upload
      :limit="1"
      accept=".xlsx,.xls,.XLSX,.XLS"
      :headers="upload.headers"
      :action='upload.url'
      :disabled="upload.isUploading"
      :before-upload="handleBeforeFileUpload"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="true"
      v-loading="upload.loading"
      drag>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip text-center" slot="tip">
        <div><strong>仅支持中文标题的数据文件导入</strong></div>
      </div>
    </el-upload>
    <el-divider></el-divider>
    <div style="padding-bottom: 30px;">
      <h3 style="color: #999999;font-size: 14px;">上传进度</h3>
      <el-progress :stroke-width="18" :text-inside="true" :percentage="upload.uploadPercent"></el-progress>
      <h3 style="color: #999999;font-size: 14px;">导入进度</h3>
      <el-progress :stroke-width="18" :text-inside="true" :percentage="upload.importPercent"></el-progress>
    </div>
  </ele-modal>
</template>


<script setup>
import {ref, reactive, watch} from 'vue';
import {EleMessage} from 'ele-admin-plus';
import {useFormData} from '@/utils/use-form-data';
import {selectCurrentYear, selectGraduationYear} from "@/api/manage/statistic/admin/schoolInfo/index.js";
import {parseTime} from "@/utils/linyang.js";
import {getToken} from "@/utils/token-util.js";
import {importStudentInfoProgress, importStudentInfo} from '@/api/manage/statistic/admin/fileInfo'

/** 弹窗是否打开 */
const visible = defineModel({type: Boolean});


/** 表单数据 */
const [form, resetFields, assignFields] = useFormData({
  date: parseTime(new Date(), '{y}-{m}-{d}'),
  year: '',
});

/** 表单验证规则 */
const rules = reactive({
  // fileYear: [
  //   {
  //     required: true,
  //     message: '请输入毕业年份',
  //     type: 'string',
  //     trigger: 'blur'
  //   }
  // ]
});

const graduationYearList = ref([]);

/**
 * 查询后台配置的毕业年份
 */
const getGraduationYear = () => {
  selectGraduationYear().then(res => {
    graduationYearList.value = res;
  });
};

getGraduationYear();

const currentYear = ref('');

const getCurrentYear = () => {
  selectCurrentYear().then(res => {
    currentYear.value = res;
    form.year = currentYear.value;
  });
}

getCurrentYear();


const upload = reactive({
  headers: {Authorization: getToken()},
  url: import.meta.env.VITE_API_URL + "/admin/employment/statistic/fileInfo/uploadData",
  isUploading: false,
  uploadPercent: 0,
  importPercent: 0,
  loading: false,
});

const uploadResult = reactive({
  successNum: 0,
  failureNum: 0,
  countNum: 0,
  resultFileName: ''
});


const handleBeforeFileUpload = (rawFile) => {
  if (!form.year) {
    EleMessage.warning({message: "未选定文件所属毕业年份", plain: true});
    return;
  }
  upload.loading = true;
  //console.log("upload.url", upload.url);
}

const handleFileUploadProgress = (event, file, fileList) => {
  upload.uploadPercent = (event.loaded / event.total * 100) | 0
  upload.isUploading = true;
}

let handleInterval = null;

const handleFileSuccess = (res, file, fileList) => {
  upload.isUploading = false;
  EleMessage.success({message: "数据上传成功，正在执行导入！", plain: true});
  let data = {fileName: res.msg, year: form.year, date: new Date()};
  if (form.date) {
    data.date = form.date;
  }
  handleInterval = setInterval(function () {
    importStudentInfoProgress(res.msg).then(res2 => {
      console.log("importStudentInfoProgress res2", res2);
      let _percent = parseInt(res2.msg);
      if (!isNaN(_percent)) {
        upload.importPercent = _percent;
      }
    });
  }, 2000);
  //发起数据导入
  importStudentInfo(data).then(res3 => {
    if (handleInterval) {
      clearInterval(handleInterval);
      handleInterval = null;
    }
    //进入到这里面代表导入结束
    upload.importPercent = 100;
    upload.isUploading = false;
    upload.loading = false;
    //TODO 暂时不处理
    //this.$refs.upload.clearFiles();//清除上传的文件显示
    EleMessage.success({message: "数据导入成功！", plain: true});
    uploadResult.successNum = res3.data.successNum;
    uploadResult.failureNum = res3.data.failureNum;
    uploadResult.countNum = res3.data.countNum;
    uploadResult.resultFileName = res3.data.resultFileName;
    //TODO 弹出框告知导入结束，并下提供下载文件地址
    // this.resultDialogVisible = true;
  }).catch((e) => {
    upload.isUploading = false;
    upload.loading = false;
    clearInterval(handleInterval);
    handleInterval = null;
    upload.importPercent = 0;
    upload.uploadPercent = 0;
    EleMessage.error({message: e.message, plain: true});
  });
}


// const handleFileSuccess = (res, file, fileList) => {
//
// }


</script>

<style>
.statistic-file-import-form-inline .el-input {
  --el-input-width: 220px;
}

.statistic-file-import-form-inline .el-select {
  --el-select-width: 220px;
}

.showOrHid {
  margin-left: 15px;
}

.el-upload--text {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
}

.el-progress__text {
  color: #999999;
  font-size: 13px !important;
}

.demonstration {
  font-weight: bold;
}
</style>
